
import api from '../../../api/index'
import { userInfoStore } from '../../../store/userInfo'

const app = getApp()

Page({

  data: {
    userLevel: 0,
    contractId: 0,
    data:{},
    indoor:[],
    outdoor:[],
    air:[],
    port:[],
    canUseCoupons: null,
    mayBuyCoupons: null,
    selectCoupons:[],
    showCouponView:false,
    showInputToast: false,
    realName:'',
  },
  
  onLoad: function (option) {
    let self = this 
    this.setData({ userLevel: userInfoStore.userInfo.level, contractId: option.id })
  },

  onShow:function(){
    if(this.data.contractId != 0)
    this.getContractInfo();
  },

  getContractInfo:function(){
    let self = this
    
    let param = {
      openId: userInfoStore.userInfo.openId,
      contractId: this.data.contractId
    }
    api.getContractInfo(param).then(res => {
      let indoor = []
      let outdoor = []
      let air = []
      let port = []
      let items = res.result.machines;
      for (let i = 0; i < items.length; i++) {
        let item = items[i]
        if (item.maichine_style == '内机') {
          if (0 == indoor.length) {
            item.showSeries = item.series
            item.showtitle = '室内机'
          }
          indoor.push(item)
        }
        if (item.maichine_style == '外机') {
          if (0 == outdoor.length) item.showtitle = '室外机'
          outdoor.push(item)
        }
        if (item.maichine_style == '新风') {
          if (0 == air.length) {
            item.showSeries = item.series
            item.showtitle = '新风系统'
          }
          air.push(item)
        }
        if (item.maichine_style == '配件') {
          if (0 == port.length) {
            item.showSeries = item.series
            item.showtitle = '配件'
          }
          port.push(item)
        }
      }
      
      if (res.result.proposal.use_status == 10){
        self.setData({
          data: res.result,
          indoor: indoor,
          outdoor: outdoor,
          air: air,
          port: port,
          canUseCoupons: null,
          mayBuyCoupons: null,
          showCouponView:false,
          realName: res.result.proposal.customer_name
        },()=>{
          self.showCoupon();
        });
      }else{
        self.setData({
          data: res.result,
          indoor: indoor,
          outdoor: outdoor,
          air: air,
          port: port,
          realName: res.result.proposal.customer_name
        });
      }

    });
  },

  showCoupon:function() {
    if (this.data.contractId == 0) return;
    if (this.data.data.contract.status != 0) return;

    if(this.data.showCouponView) {
      this.setData({
        canUseCoupons: null,
        mayBuyCoupons: null,
        showCouponView:false,
      })
      return;
    }

    let self = this
    let param = {
      id: this.data.data.contract.proposalId,
      user_id: userInfoStore.userInfo.id,
      office_id: this.data.data.contract.distributorId
    }
    api.getCouponInfoByProposal(param).then(res => {
      let { coupons, userCoupons} = res.result;
      let cps = [];
      let find = false;
      for (var i = 0; i < coupons.length;i++){
        find = false;
        for (let j = 0; j < userCoupons.length;j++){
          if (coupons[i].id == userCoupons[j].couponId){
            find = true;
            break;
          }
        }
        if (!find) cps.push(coupons[i]);
      }
      self.setData({
        canUseCoupons: userCoupons,
        mayBuyCoupons: cps,
        showCouponView: true,
      });

    });
  },

  useCoupon:function(e){
    let rds;
    let item = e.currentTarget.dataset.item; 
    for (let i = 0; i < this.data.canUseCoupons.length; i++) {
      rds = this.data.canUseCoupons[i];
      if (rds.id == item.id) {
        rds.select = !rds.select;
      }
      if (rds.select) {
        this.data.selectCoupons.push(rds.id)
      }
    }
    this.setData({
      canUseCoupons: this.data.canUseCoupons,
      selectCoupons: this.data.selectCoupons,
    })
  },

  setNameValue:function(e){
    this.setData({
      realName: e.detail.value
    })
  },

  toastCancel:function(){
    this.setData({
      showInputToast: false
    })
  },

  toastConfirm:function(){
    // console.log(this.data.selectCoupons);
    if(this.data.realName.length == 0){
      wx.showToast({
        icon: "none",
        title: "请填写您的真实姓名!"
      })
      return;
    }

    let self = this
    let param = {
      openId: userInfoStore.userInfo.openId,
      contractId: this.data.data.contract.id
    };
    if (this.data.selectCoupons.length > 0)
      param = Object.assign(param, { userCouponIds: this.data.selectCoupons.join(',') })

    let p = {
      openId: userInfoStore.userInfo.openId,
      id: self.data.data.contract.id,
      userName: this.data.realName, 
    }

    api.modifyContractBaseInfo(p).then(res => {
      api.confirmContract(param).then(res => {
        self.setData({
          showInputToast: false
        }, ()=>{
          self.getContractInfo();
        })
      });
    })
  },

  sumbit:function(){
    this.setData({
      showInputToast: true
    })
  },

  reject: function(){
    let self = this
    wx.showModal({
      title: '提示',
      content: '确认驳回吗?',
      showCancel: true,
      success: (res) => {
        let param = {
          openId: userInfoStore.userInfo.openId,
          contractId: self.data.data.contract.id
        };
        api.rejectContract(param).then(res => {
          self.data.data.contract = res.result;
          self.setData({
            data:self.data.data,
            canUseCoupons:null,
            mayBuyCoupons:null,
            selectCoupons:[]
          })
        }) 


      }
    });    

  },

  gobuy: function (e) {
    if (!this.data.data.contract) return;
    if (this.data.data.contract.status != 0) return;
    let item = e.currentTarget.dataset.item;

    wx.navigateTo({
      url: '../../coupon/detail?couponId=' + item.id,
    })
  },

  showCouponDetail:function(e){
    if (!this.data.data.contract) return;
    let couponId = e.currentTarget.dataset.cid;
     wx.navigateTo({
       url: '../../coupon/detail?couponId=' + couponId,
     })
  },

  openFile:function(e){
    let path = e.currentTarget.dataset.path;
    if(path=='null' || path.length==0){
      wx.showModal({
        title: '提示',
        content: '文件发生错误',
      })
      return;
    }
    if(path.substring(0,7) == 'http://'){
      path = 'https://' + path.substring(7);
    }
    
    // wx.navigateTo({
    //   url: '../../webView/index?url=' + encodeURIComponent(path),
    // })
    wx.downloadFile({
      url: path,
      success: function (res) {
        var filePath = res.tempFilePath
        wx.openDocument({
          filePath: filePath,
          fileType: "pdf",
          success: function (res) {

            console.log('打开文档成功')

          }
        })
      }
    })
  },

  goSign:function(e){
    
    let content = "接下来会进入合同签署流程，该合同为您与"+this.data.data.distributor.name+"签署，大金提供平台支持。请仔细阅读合同条款，是否为之前约定内容，如有疑问请致电经销商修改。该合同一经签署将立刻生效，且具有纸质合同同等法律效力，请按时履约，谢谢！";
    let dialog = this.selectComponent("#dialog");

    dialog.show(content);
    
  },

  dialogConfirm: function (e) { 
    if (!this.data.data.contract) return;
    let id = this.data.data.contract.id;
    api.getSignFilePath({ contractId: id }).then(res => {
      if (res.result && res.result != 'null') {
        
        wx.navigateTo({
          url: '../../webView/index?url=' + encodeURIComponent(res.result),
        })
      }else{
        wx.showModal({
          title: '提示',
          content: '签约发生错误',
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    getApp().share();
  }
})